package com.cdu.xinmiao.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cdu.xinmiao.R;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.xuexiang.xui.widget.actionbar.TitleBar;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DakaActivity extends AppCompatActivity {
    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int REQUEST_QR_SCAN = 2;
    private TitleBar titleBar;
    private ImageView mImageView;
    private Button scanButton;
    private TextView mDakaSuccessTextView;
    private TextView mTimeTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_daka);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.daka), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        getId();

        bindClick();

        // 检查设备是否有相机
        if (!hasCamera()) {
            Toast.makeText(this, "设备没有相机", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建 Intent 来启动相机应用
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 确保有应用能够处理相机意图
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // 启动相机应用并等待结果
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

    private void bindClick() {
        titleBar.setLeftClickListener(v -> finish());
        scanButton.setOnClickListener(v -> startScan());
    }

    private void getId() {
        titleBar = findViewById(R.id.titleBar_back);
        mImageView = findViewById(R.id.imageView);
        scanButton = findViewById(R.id.scanButton);
        mDakaSuccessTextView = findViewById(R.id.dakaSuccessTextView);
        mTimeTextView = findViewById(R.id.timeTextView);
    }

    private boolean hasCamera() {
        return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
    }

    private void startScan() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        IntentIntegrator integrator = new IntentIntegrator(this);
        integrator.setOrientationLocked(false);
        integrator.setPrompt("扫码验证");
        integrator.setRequestCode(REQUEST_QR_SCAN);
        integrator.initiateScan();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            mImageView.setImageBitmap(imageBitmap);
            // 设置打卡成功提示可见
            mDakaSuccessTextView.setVisibility(View.VISIBLE);
            updateCaptureTime();
        } else if (requestCode == REQUEST_QR_SCAN) {
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result != null) {
                if (result.getContents() != null) {
                    Toast.makeText(this, "扫码结果: " + result.getContents(), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "取消扫码", Toast.LENGTH_LONG).show();
                }
            } else {
                Toast.makeText(this, "无结果", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void updateCaptureTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String currentTime = sdf.format(new Date());
        mTimeTextView.setText(currentTime);
    }
}
